<template>
	<ul class="sider-ul" :style="{'height':height}">
		<template v-for="level1 in routeList">
			<li class="menu-items" :id="'menu-'+level1.name" :key="level1.name" v-if="level1.hidden">
				<div @click.stop="changeMenuItem(level1)" class="menu-item-wrap" :class="{menuItemActive:showMark(level1)}">
					<Icon v-if="level1.icon" :type="level1.icon" :class="handleClass(level1,'icon')" :size="18"></Icon>
					<div v-else :class="handleClass(level1)"></div>
					<div class="item-text">{{level1.title}}</div>
					<div class="long-line-active"></div>
				</div>
				<!--二级-->
				<div class="submenu-wrap" :class="{showSubMenu:showMark(level1)}" v-if="hasChildren(level1)">
					<template v-for="level2 in level1.children">
						<div class="submenu-item" :key="level2.name" :id="'menu-'+ level2.name" :class="{colorOrange:showMark(level2)}" v-if="level2.hidden && !hasChildren(level2)" @click.stop="changeMenuItem(level2,level1)">
							<div class="short-active-line"></div>
							{{level2.title}}
						</div>
						<!--三级-->
						<div class="submenu-item" :key="level2.name" v-if="level2.hidden && hasChildren(level2)">
							<div>
								<div class="ring-style"></div>
								{{level2.title}}
							</div>
							<template v-for="level3 in level2.children">
								<div :id="'menu-'+level3.name" v-if="level3.hidden" :key="level3.name">
									<div style="margin-left: 20px;line-height: 2.3" :class="{colorOrange:showMark(level3)}" @click.stop="changeMenuItem(level3,level1)">
										<div class="short-active-line"></div>
										{{level3.title}}
									</div>
								</div>
							</template>
						</div>
					</template>
				</div>
			</li>
		</template>
	</ul>
</template>
<script>
    import {mapMutations} from 'vuex'
	export default {
		name: 'SideMenu',
		mixins: [],
		components: {

		},
		props: {
			activeNames: {
				type: Array,
				default: () => []
			},
			routeList: {
				type: Array,
				default: () => []
			},
			height: ''
		},
		data() {
			return {
				activeMenuList: [],
				menuListAll:[],
				menuListAllHidden:[],
				menuListAllShow:[]
			}
		},
		methods: {
			...mapMutations(["setMenuInfo"]),
			showMark(menu) {
				return this.activeMenuList.includes(menu.name);
			},
			hasChildren(menu){
				return menu.children && menu.children.filter(menu => menu.hidden).length > 0;
			},
			//			markRoute(activeList, routeList) {
			//				routeList.forEach(route => {
			//					if(activeList.includes(route.name) && route.hidden) {
			//						route.meta.mark = true
			//					} else {
			//						if(route.meta) {
			//							route.meta.mark = false
			//						}
			//					}
			//					if(route.children) {
			//						this.markRoute(activeList, route.children)
			//					}
			//				})
			//			},
			flatDeep(arr, d = 1, result = []) {
				if(d > 0) {
					for(let item of arr) {
						if(Array.isArray(item.children)) {
							result.push(item)
							this.flatDeep(item.children, Infinity, result)
						} else {
							result.push(item)
						}
					}
					return result
				} else {
					return arr.slice();
				}
			},
			routeHasHidden(name) {
				return this.menuListAllHidden.find(menu => menu.name == name);
			},
			//根据子菜单获取一级菜单
			getLevel1Menu(name) {
				let menu = this.menuListAll.find(route => route.name == name);
				if(menu && menu.parentRoute) {
					return this.getLevel1Menu(menu.parentRoute.name);
				} else {
					return menu;
				}
			},
			gotoOtherShowRoute(name) {
				//获取当前菜单信息
				let menuInfo = this.menuListAll.find(route => route.name == name);
				if(menuInfo && menuInfo.parentRoute) { //如果当前菜单是子菜单（二级/三级）
					//获取一级父菜单信息
					let level1Menu = this.getLevel1Menu(menuInfo.name);
					//获取父级菜单
					let pmenu = menuInfo.parentRoute;
					if(level1Menu.hidden) { //如果一级菜单显示
						if(menuInfo.level == 2) { //二级
							//获取对当前菜单的同级菜单
							let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
							let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
							if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
								let firstShowRoute = siblingsShowMenu;
								this.changeMenuItem(firstShowRoute, level1Menu);
							} else {
								this.gotoOtherShowRoute(level1Menu.name);
							}
						} else { //三级
							if(pmenu.hidden) {//二级菜单显示
								let siblingsMenu = menuInfo.parentRoute.children;//this.menuListAll.filter(menu => menu.pid == menuInfo.pid);
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute, level1Menu);
								}
							} else { //二级菜单隐藏
								//获取父级菜单的兄弟菜单
								let siblingsMenu = level1Menu.children;
								let siblingsShowMenu = siblingsMenu.find(menu => menu.hidden && menu.hidden != undefined);
								if(siblingsShowMenu) { //如果兄弟菜单中有显示的菜单
									let firstShowRoute = siblingsShowMenu;
									this.changeMenuItem(firstShowRoute.children ? firstShowRoute.children[0] : firstShowRoute);
								} else {
									this.gotoOtherShowRoute(level1Menu.name);
								}
							}
						}
					} else { //一级菜单隐藏
						this.gotoOtherShowRoute(level1Menu.name);
					}
				} else {
					let firstShowRoute = this.menuListAllShow.length > 0 ? this.menuListAllShow[0] : '';
					if(firstShowRoute) { //有显示的路由
						this.changeMenuItem(firstShowRoute);
					} else {
						this.$Message.warning('没有可用的菜单');
						setTimeout(() => {
							this.$emit('on-select', 'login')
						})
					}
				}
			},
			// 设置icon
			handleClass(value,type) {
				let {
					defClass,
					activeClass,
					mark
				} = value.meta;
				return this.showMark(value) ? (type == 'icon' ? 'icon-active' : activeClass) : (type == 'icon' ? 'icon-def' : defClass)
			},
			// 切换导航栏
			changeMenuItem(menu, level1Menu) { //当前菜单，一级菜单
				let name = menu.name;
				let level = menu.level;
				let children = menu.children;
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				if(level == 1) {
					// 切换时是否跳到上次点击的子菜单栏
					let prevMarkName = markMenuObj[name];
					if(prevMarkName) {
						this.$emit('on-select', prevMarkName)
					} else {
						this.$emit('on-select', name)
					}
				} else {
					this.$emit('on-select', name)
				}
			},
			getActiveMenuList(name,list = []){ //根据当前菜单找到所有的父级菜单
				if(!name){
					return list;
				}
				let menu = this.menuListAll.find(route => route.name == name);
				list.unshift(name);
				if(menu && menu.parentRoute) {
					let pMenu = menu.parentRoute;
					return this.getActiveMenuList(pMenu.name,list);
				} else {
					return list;
				}
			},
			initRoute(){ //设置当前mark的菜单列表及菜单显示位置
				let activeMenuList = this.$route.matched.map(item => item.name).filter(item => item !== 'main');
				let storageMenuList = sessionStorage.getItem('activeMenuList');
				storageMenuList = storageMenuList && JSON.parse(storageMenuList) || [];
				let markMenuObj = sessionStorage.getItem('markMenuObj') ? JSON.parse(sessionStorage.getItem('markMenuObj')) : {};
				let activeName = '';
				if(activeMenuList.length > 0) {
					if(activeMenuList[0] == 'parentView') { //非菜单页
						//多个路由跳转同一个页面配置
						let setActiveMenuList = []
						if(typeof this.$route.meta.activeName=='string'){
							setActiveMenuList = this.getActiveMenuList(this.$route.meta.activeName);
						}else if(this.$route.query.fromMenu){
							let fromMenu = this.$route.query.fromMenu
							setActiveMenuList = this.getActiveMenuList(fromMenu);
						}else{
							setActiveMenuList = this.getActiveMenuList(this.$route.meta.activeName[0]);
						}
						//let setActiveMenuList = this.getActiveMenuList(this.$route.meta.activeName);
						if(JSON.stringify(storageMenuList) != JSON.stringify(setActiveMenuList)){ //如果详情页设置的高亮菜单和存储的高亮菜单不一致,说明详情页需要高亮的菜单和当前高亮的菜单不匹配（以详情页为主）
							if(setActiveMenuList.length > 0){
								this.activeMenuList = setActiveMenuList; //重新设置触发菜单
								let isAccess = this.$route.meta.isAccess || [];
								if(!isAccess.some(menu => storageMenuList.includes(menu))){ //如果form的菜单不允许直接跳到当前页面
									activeName = this.activeMenuList[this.activeMenuList.length - 1]; //回菜单页
									this.$router.push(activeName);
								}
//								sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList));
//								if(this.activeMenuList.length > 1) {
//									markMenuObj[this.activeMenuList[0]] = activeName;
//									sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
//								}
							}else{
								if(storageMenuList.length > 0) {
									this.activeMenuList = storageMenuList;
									activeName = this.activeMenuList[this.activeMenuList.length - 1];
								} else {
									let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
									this.$emit('on-select', toName);
									return;
								}
							}
						}else{
							if(storageMenuList.length > 0) {
								this.activeMenuList = storageMenuList;
								activeName = this.activeMenuList[this.activeMenuList.length - 1];
							} else {
								let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
								this.$emit('on-select', toName);
								return;
							}
						}
					} else { //菜单页
						this.activeMenuList = activeMenuList;
						activeName = this.activeMenuList[this.activeMenuList.length - 1];
						//记录当前菜单
						sessionStorage.setItem('activeMenuList', JSON.stringify(this.activeMenuList))
						if(activeMenuList.length > 1) {
							markMenuObj[this.activeMenuList[0]] = activeName;
							sessionStorage.setItem('markMenuObj', JSON.stringify(markMenuObj));
						}
					}
				} else {
					if(storageMenuList.length > 0) {
						this.$emit('on-select', storageMenuList[storageMenuList.length - 1])
						return;
					} else {
						let toName = this.routeList.length > 0 ? this.routeList[0].name : 'main'
						this.$emit('on-select', toName)
						return;
					}
				}
				if(this.routeHasHidden(activeName)) {
					this.gotoOtherShowRoute(activeName);
					return;
				}
				//菜单滚动位置
				this.$nextTick(() => {
					let oUl = document.getElementsByClassName("sider-ul")[0];
					let el = document.getElementById('menu-' + this.activeMenuList[0]);
					if(oUl && el) {
						oUl.scrollTop = (el.offsetTop - oUl.offsetTop) - (oUl.offsetHeight - el.offsetHeight) / 2;
					}
				})
			},
			setMenuLevel(routeList,parentRoute,level = 0){
				level++;
				routeList.forEach(route => {
					route.level = level;
					if(parentRoute){
						route.parentRoute = parentRoute;
					}
					if(route.children && route.children.length > 0){
						this.setMenuLevel(route.children,route,level);
					}
				})
			},
		},
		computed: {

		},
		beforeDestroy() {
			sessionStorage.removeItem('markMenuObj');
			sessionStorage.removeItem('activeMenuList');
		},
		updated() {

		},
		watch: {
			activeNames(val) {
				this.initRoute();
			},
			activeMenuList(val){
				if(val.length > 0){
					let menuInfo = this.menuListAllShow.find(menu => menu.name === val[val.length - 1])
					// 存储当前菜单信息，用于菜单页title显示（title与菜单名保持一致）
					this.setMenuInfo(menuInfo);
				}
			},
			routeList(val) {
				this.setMenuLevel(val);
				this.menuListAll = this.flatDeep(val, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
			}
		},
		mounted() {
			if(this.routeList.length > 0){
				this.setMenuLevel(this.routeList);
				this.menuListAll = this.flatDeep(this.routeList, Infinity);
				this.menuListAllHidden = this.menuListAll.filter(menu => !menu.hidden && menu.hidden != undefined); //所有隐藏的菜单，无层级
				this.menuListAllShow = this.menuListAll.filter(menu => menu.hidden); //所有未被隐藏的菜单，无层级
				this.initRoute();
				
			}
		}
	}
</script>
<style scoped>
	/*菜单栏样式*/
	
	.sider-ul {
		/* height: calc(100% - 175px - 307px); */
		overflow-y: auto;
		position: static;
		overflow-x: hidden;
		scrollbar-width: none;
	}
	
	.sider-ul::-webkit-scrollbar {
		width: 0;
	}
	
	.menu-items {
		cursor: pointer;
		position: relative;
		z-index: 0;
	}
	
	.menuItemActive {
		background-color: rgb(238, 235, 249);
	}
	
	.menu-item-wrap {
		position: relative;
		z-index: 5;
		display: flex;
		/*justify-content: center;*/
		width: 100%;
    	padding: 0 30px;
	}
	
	.item-text {
		margin: 0 0 0 15px;
		color: #8f90a6;
		font-weight: 400;
		height: 60px;
		line-height: 60px;
		/*width: 90px;*/
		font-size: 16px;
		word-break: break-all;
		white-space: nowrap;
	    overflow: hidden;
	    text-overflow: ellipsis;
	}
	
	.menuItemActive .item-text {
		color: #333333;
		font-weight: bold;
		font-weight: 600
	}
	
	.submenu-wrap {
		text-align: center;
		display: none;
		position: relative;
		z-index: 4;
	}
	
	.showSubMenu {
		display: block;
	}
	
	.submenu-item {
		padding-top: 10px;
		text-align: left;
		color: #8f90a6;
		padding-left: 48px;
	}
	
	.long-line-active {
		position: absolute;
		top: 0;
		right: 0;
		height: 60px;
		width: 4px;
		background-color: rgb(78, 48, 121);
		visibility: hidden;
	}
	
	.menuItemActive .long-line-active {
		visibility: visible;
	}
	
	.ring-style {
		height: 6px;
		width: 6px;
		background-color: rgb(140, 166, 246);
		border-radius: 50%;
		display: inline-block;
		margin-bottom: 2px;
		margin-right: 5px;
	}
	
	.colorOrange {
		color: #333333;
		font-weight: bold;
	}
	
	.short-active-line {
		height: 16px;
		width: 4px;
		background-color: rgb(78, 48, 121);
		display: inline-block;
		margin-bottom: -2px;
		margin-right: 10px;
		visibility: hidden;
	}
	
	.colorOrange .short-active-line {
		visibility: visible;
	}
	.icon-def{
		line-height:60px;
		width: 24px;
		height: 57.5px;
		text-align: center;
		color:#8f90a6;
	}
	.icon-active{
		line-height:60px;
		width: 24px;
		height: 57.5px;
		text-align: center;
		color:#2518b8;
	}
</style>
<style scoped src="./menu-icon.css">